<template>
	<view class="response">
		<view @click="open">
			  <view v-if="showSelectItem" class="flex align-center justify-end">
				<view class="margin-right-xs text-gray" v-if="!selectItems.length">
					{{ placeholder }}
				</view>
				<template v-else>
					<slot name="label" v-bind="{ selectItems }">
						{{ selectItems.map((item) => item[labelName]).join(',') }}
					</slot>
				</template>
				<slot name="icon" v-bind="{ onClear }">
					<view>
						<uni-icons v-if="clearable && selectItems.length" class="content-clear-icon" type="clear" :size="24"
						color="#c0c4cc" @click.native.stop="onClear"></uni-icons>
						<uni-icons type="right" size="20" color="#8799a3"></uni-icons>
					</view>
				</slot>
			  </view>
		</view>
		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup"  @maskClick="onPopupClose">
				<view class="bg-white padding-top bottom-popup">
					<view class="bg-white padding-sm text-center solid-bottom text-lg text-black flex">
					            <view class="response">
					                {{placeholder}}
					            </view>
					            <view @click="close" class="fr round" style="background-color: #F2F2F2;width: max-content;padding-left: 10rpx;padding-right: 10rpx; padding-top: 5rpx;">
					                <uni-icons type="closeempty" size="15" color="#666666"></uni-icons>
					            </view>
					        </view>
					<view class="content" :style="contentStyles">
						<z-paging ref="paging" v-model="optionsData" @query="queryList" style="top: 40px">
							<view slot="top">
								<view class="solid-top margin-top">
									<view class="flex padding-tb-xs bg-white">
										<view class="flex-sub cu-bar search">
											<view class="search-form round padding-lr" style="margin: 0 10px;background-color: #F2F2F2;height: 40px;">
												<input style="height: 40px;" v-model="searchValue" :adjust-position="false" type="text" :placeholder="searchPlaceholder"></input>
												<uni-icons class="margin-left-xs" type="search" size="19"></uni-icons>
											</view>
										</view>
										<view v-if="addEvent" class="padding-right flex align-center" @click="addEvent">
											<uni-icons class="margin-left-xs" type="plus" size="26" color="#1D39C4"></uni-icons>
										</view>
									</view>
								</view>
							</view>
							<view class="margin-top-sm">
								<scroll-view scroll-y="true" :style="listStyles">
									<view class="padding-bottom">
											<view class="bg-white">
												<view v-for="(item,index) in optionsData" @click="select(item)">
													<uni-list-item clickable>
														<!-- 自定义 body -->
														<template v-slot:body>
															<view class="text-center text-lg text-black flex response">
																<view class="margin-right-lg" v-if="multiple">					
																	<checkbox class="blue" :class="selectItemsMapValue.includes(item[valueName]) ? 'checked' : ''" style="transform:scale(0.7)"></checkbox>
																</view>
																<view class="flex flex-sub justify-between">
																	<view class="flex-sub text-left">
																		<slot name="item" v-bind="{ item }">
																			<view class='cu-tag round light' :class="'bg-' + item.colorType">{{item[labelName]}}</view>
																		</slot>
																	</view>
																	<view class="flex align-center margin-left-sm" :style="{'visibility': !multiple && selectItemsMapValue.includes(item[valueName]) ? 'visible' : 'hidden'}">
																		<uni-icons type="checkmarkempty" size="21" color="#007AFF"></uni-icons>
																	</view>
																</view>
															</view>
														</template>
													</uni-list-item>
												</view>
												<view v-if="isEmpty" class="text-center padding-lg">
													暂无数据
												</view>
											</view>
										</view>
								</scroll-view>
							</view>
						</z-paging>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	export default {
		emits: ['update:modelValue'],
		model: {
			prop: 'modelValue', // 对应 props msg
			event: 'update:modelValue'
		},
		props: {
			modelValue: {
				type: [Object, String, Array],
				default: ()=>{
					return {};
				}
			},
			showSelectItem: {
				type: Boolean,
				default: true
			},
			// 标题
			title: {
				type: String,
				default: '请选择'
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			searchPlaceholder: {
				type: String,
				default: '请选择'
			},
			searchName: {
				type: String,
				default: 'name'
			},
			// 是否多选
			multiple: {
				type: Boolean,
				default: false	
			},
			labelName: {
				type: String,
				default: 'name'
			},
			valueName: {
				type: String,
				default: 'id'
			},
			api: {
				type: Function,
				default: function() {}
			},
			listField: {
				type: String,
				default: 'list'
			},
			pageField: {
				type: String,
				default: 'pageNo'
			},
			sizeField: {
				type: String,
				default: 'pageSize'
			},
			totalField: {
				type: String,
				default: 'total'
			},
			// 是否可清空
			clearable: {
				type: Boolean,
				default: true
			},
			// 添加事件
			addEvent: {
				type: Function
			}
		},
		data() {
			return {
				optionsData: [],
				selectItems: [],
				screenHeight: 0,
				searchValue: '',
				pageParams: {
					[this.pageField]: 1,
					[this.sizeField]: 10
				}
			};
		},
		computed: {
			contentStyles() {
				return `height: calc(${this.screenHeight}px - 200px)`;
			},
			listStyles() {
				return `height: calc(${this.screenHeight}px - 260px)`;
			},
			selectItemsMapValue() {
				return this.selectItems.map(item=> item[this.valueName]) || []
			},
			// 是否空数据
			isEmpty() {
				return this.optionsData.length === 0;
			}
		},
		watch: {
			modelValue: {
                immediate: true,
                handler(newVal,oldVal) {
					if(!newVal) return
					if(newVal!=oldVal){
						if(newVal instanceof Array) {
							this.selectItems = newVal
						} else {
							this.selectItems = newVal[this.valueName] ? [newVal] : []
						}
                    }
                }
            },
			 searchValue: {
			     handler(newVal, oldVal) {
			       console.log('[DEBUG] SearchValue changed:', newVal); // 打印调试信息
			       if (newVal !== oldVal) {
			         setTimeout(() => {
			           this.reload(); // 确保触发重新加载数据
			         }, 10); // 添加延迟，确保数据绑定完成
			       }
			     }
			   }
		},
		mounted() {
			var that = this
			uni.getSystemInfo({
				success: function (res) {
					that.screenHeight = res.windowHeight - res.statusBarHeight
				}
			});
		},
		methods: {
			queryList(query) {
				var that = this
				console.log(that.searchValue, 'searchValuequeryList');
				console.log(query, 'query');
				this.api({
					...this.pageParams,
					[this.pageField]: query,
					[this.searchName]: this.searchValue,
				}).then(({data}) => {
					this.$refs.paging.complete(data[that.listField]);
					})
			},
			open(){
				this.$refs.popup.open('bottom')
			},
			close(){
				this.searchValue = ''
				this.$refs.popup.close()
			},
			onPopupClose() {
				this.searchValue = ''
			},
			onClear() {
				this.selectItems = []
				this.$emit('update:modelValue', null)
			},
			// 刷新
			reload() {
				console.log('[DEBUG] Reload called', this.$refs.paging.reload);
				setTimeout(() => {
					this.$refs.paging.reload()
					this.queryList(1)
				}, 10)
			},
			select(item) {
				const that = this;
				if (that.multiple) {
					let index = that.selectItems.findIndex(it => it[that.valueName] == item[that.valueName]);
					if (index == -1) {
						that.selectItems.push({ ...item }); // 使用浅拷贝
					} else {
						that.selectItems.splice(index, 1);
					}
					that.$emit('update:modelValue', [...that.selectItems]); // 保证是数组
				} else {
					that.selectItems = [{ ...item }]; // 使用浅拷贝
					that.$emit('update:modelValue', { ...item }); // 保证是对象
					that.close();
					
				}
				this.searchValue = ''
			}
		},
	}
</script>

<style lang="scss">
	.bottom-popup {
		border-top-left-radius: 20upx;
		border-top-right-radius: 20upx;
	}
	.content {
		background-color: #F2F2F2;
	}
	.scroll-Y {
		height: 100px;
	}
</style>